<template>
	<view class="bg-box">
		<image src="/static/images/login_bg.jpg" mode="aspectFill" class="img"></image>
	</view>
	<view class="container">
		<view class="back-box" @click="back">
			<image src="/static/images/icon_back.png" mode="aspectFill" class="img"></image>
		</view>
		<view class="j-center mt-100">登录</view>
	</view>
	<uv-notice-bar text="请文明使用小程序,共同营造美好氛围" mode="closable"></uv-notice-bar>
	<view class="mt-10"></view>
	<uv-notice-bar text="目前为测试版本,暂时无法上传头像等数据" mode="closable"></uv-notice-bar>
	<view class="container">
		<view class="welcome-text mt-50 j-center">欢迎使用大学生社交小程序</view>
		<view class="j-center">
			<view class="mt-50 login-box" v-if="!is_enroll">
				<view class="j-center blod-text" v-if="is_login">登录</view>
				<view class="j-center blod-text" v-if="!is_login">注册</view>
				<view class="mt-30 j-center">
					<view class="a-center">账号：</view>
					<uv-input placeholder="请输入账号" border="surround" v-model="account"></uv-input>
				</view>
				<view class="mt-30 j-center">
					<view class="a-center">密码：</view>
					<uv-input placeholder="请输入密码" border="surround" v-model="password" password></uv-input>
				</view>
				<view class="flex-end mt-30 login-tips-text" @click="handoff" v-if="is_login">还没有账号？去注册</view>
				<view class="flex-end mt-30 login-tips-text" @click="handoff" v-if="!is_login">返回登录！</view>
				<view class="mt-30" v-show="is_login">
					<uv-button type="success" text="登录" @click="login"></uv-button>
				</view>
				<view class="mt-30" v-show="!is_login">
					<uv-button type="success" text="注册" @click="enroll"></uv-button>
				</view>
			</view>
			<view class="mt-50 login-box" v-if="is_enroll">
				<view class="j-center blod-text">注册信息表</view>
				<view class="mt-30 j-center">
					<view class="a-center">名称：</view>
					<uv-input placeholder="请输入内容" border="surround" v-model="name"></uv-input>
				</view>
				<view class="mt-30">选择头像(先输入名称后选择)</view>
				<view class="mt-30"></view>
				<uv-upload :fileList="fileList1" name="1" :multiple="false" :maxCount="1" @afterRead="afterRead"
					@delete="deletePic"></uv-upload>
				<view class="mt-30 flex">
					<view class="a-center">生日：</view>
					<uv-datetime-picker ref="datetimePicker" mode="date" @confirm="confirm" :maxDate="1293830400000"
						:minDate="0">
					</uv-datetime-picker>
					<view class="" @click="open">{{date || '请选择日期'}}</view>
				</view>
				<view class="flex mt-30">
					<view class="input-text a-center">性别：</view>
					<uv-tags text="男" :plain="true" icon="/static/images/man.png" @click="selectMan"></uv-tags>
					<view class="ml-30">
						<uv-tags text="女" :plain="true" borderColor="pink" color="pink" icon="/static/images/girl.png"
							@click="selectWoman"></uv-tags>
					</view>
				</view>
				<view class="flex mt-30">
					<view class="input-text a-center">已选性别：</view>
					<view class="input-text a-center">{{selected_sex}}</view>
				</view>
				<view class="input-text a-center mt-30">个性签名:</view>
				<view class="mt-10">
					<uv-textarea v-model="sign_value" count placeholder="请输入内容" maxlength="50"></uv-textarea>
				</view>
				<view class="mt-50">
					<uv-button type="success" text="确定" @click="submit"></uv-button>
				</view>
			</view>
		</view>
	</view>
	<uv-toast ref="toast"></uv-toast>
</template>

<script>
	export default {
		data() {
			return {
				name: '', // 名称
				selected_sex: '男', // 选择后的性别
				is_sure: false, // 确定按钮
				sign_value: '',
				date: '', // 生日
				user_info: {}, // 用户信息
				dateStamp: 0, // 时间戳
				is_enroll: false, // 是否注册成功
				account: '', // 用户账号
				password: '', // 用户密码
				is_login: true, // 登录
				user_img: '', // 用户头像
				fileList1: []
			}
		},
		methods: {
			back() {
				uni.navigateBack()
			},
			handoff() {
				this.is_login = !this.is_login
			},
			selectMan() {
				this.selected_sex = '男'
			},
			selectWoman() {
				this.selected_sex = '女'
			},
			open() {
				this.$refs.datetimePicker.open();
			},
			// 时间转换
			convertTimestampToDate(timestamp) {
				const date = new Date(timestamp);

				// 获取年、月、日
				const year = date.getFullYear();
				const month = ('0' + (date.getMonth() + 1)).slice(-2); // 加1是因为getMonth返回的是0-11
				const day = ('0' + date.getDate()).slice(-2);

				// 组合成想要的格式
				return `${year}-${month}-${day}`;
			},
			confirm(e) {
				this.date = this.convertTimestampToDate(e.value)
				this.dateStamp = +e.value
			},
			// 下面是上传头像
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				const user_info = uni.getStorageSync('user_info')
				for (let i = 0; i < lists.length; i++) {
					const list = {
						pathName: `images/usersAvatar/${this.name}/${Date.now()}.jpg`,
						path: lists[i].url
					}
					const result = await this.uploadFilePromise(list)
					this.user_img = result.fileID
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(item) {
				return uniCloud.uploadFile({
					cloudPathAsRealPath: true,
					cloudPath: item.pathName,
					filePath: item.path
				})
			},
			async login() {
				if (this.account.length < 10) {
					this.$refs.toast.show({
						type: 'warning',
						message: "请输入正确的账号"
					})
					return
				} else if (this.password.length < 6) {
					this.$refs.toast.show({
						type: 'warning',
						message: "请输入正确的密码"
					})
					return
				} else {
					const db = uniCloud.database();
					const collection = db.collection('user_info')
					const response = await uniCloud.callFunction({
						name: 'login',
						data: {
							account: this.account,
							password: this.password
						}
					});

					if (response.result.success) {
						const res = await uniCloud.callFunction({
							name: 'getUserInfo',
							data: {
								account: this.account
							}
						})
						uni.setStorageSync('user_info', res.result.data[0])
						this.$refs.toast.show({
							type: 'success',
							message: "登录成功，正在返回首页"
						})
						uni.navigateBack()
						uni.setStorageSync('is_login', true)
						console.log('登录成功')
					} else {
						this.$refs.toast.show({
							type: 'error',
							message: "账号或密码错误"
						})
					}
				}
			},
			async enroll() {
				if (this.account.length < 10) {
					this.$refs.toast.show({
						type: 'warning',
						message: "账号长度至少10位"
					})
					return
				} else if (this.password < 6) {
					this.$refs.toast.show({
						type: 'warning',
						message: "密码长度至少6位"
					})
					return
				}
				this.$refs.toast.show({
					type: 'success',
					message: "注册成功，请完善用户信息"
				})
				this.is_enroll = true
			},
			async submit() {
				if (!this.name) {
					this.$refs.toast.show({
						type: 'warning',
						message: "请输入名称"
					})
					return
				} else if (!this.user_img) {
					this.$refs.toast.show({
						type: 'warning',
						message: "请选择头像"
					})
					return
				} else if (!this.date) {
					this.$refs.toast.show({
						type: 'warning',
						message: "请选择日期"
					})
					return
				}
				try {
					const db = uniCloud.database();
					const collection = db.collection('user_info')
					const userInfo = {
						account: String(this.account),
						password: String(this.password),
						user_name: this.name,
						sex: this.selected_sex,
						date: String(this.date),
						sign: this.sign_value,
						user_img: this.user_img, // 用户头像
						fans: "0", // 新增：初始粉丝数为0
						collection: "0", // 新增：初始收藏数为0
						concern: "0", // 新增：初始关注数为0
						collection_list:[], // 初始化新的收藏列表
					}
					const result = await collection.add(userInfo)
					const completeUserInfo = {
						...userInfo,
						_id: result.result.id // 添加_id到用户信息中
					}
					// 将用户信息存储到缓存
					uni.setStorageSync('user_info', completeUserInfo)
					uni.setStorageSync('is_login', true)

					this.$refs.toast.show({
						type: 'success',
						message: '注册成功，正在返回首页'
					})

					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} catch (error) {
					this.$refs.toast.show({
						type: 'error',
						message: '数据提交失败'
					})
					console.error('数据提交失败', error)
				}
			}
		}
	}
</script>

<style scoped>
	.bg-box {
		width: 100%;
		height: 100%;
		position: fixed;
		z-index: -1;
	}

	.container {
		padding: 30rpx;
		position: relative;
	}

	.back-box {
		width: 60rpx;
		height: 80rpx;
		position: absolute;
		top: 100rpx;
		z-index: 3;
	}

	.welcome-text {
		font-size: 50rpx;
		font-weight: 600;
		color: #3c9cff;
	}

	.login-box {
		padding: 30rpx;
		min-width: 500rpx;
		background-color: #fff;
	}

	.login-tips-text {
		font-size: 26rpx;
		color: #3c9cff;
	}
</style>